package com.cjkj.equipment.service.impl;

import com.cjkj.common.constant.UserConstants;
import com.cjkj.common.core.domain.entity.SysDictData;
import com.cjkj.common.core.text.Convert;
import com.cjkj.common.exception.ServiceException;
import com.cjkj.common.utils.DateUtils;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.common.utils.bean.BeanUtils;
import com.cjkj.equipment.domain.Equipment;
import com.cjkj.equipment.domain.dto.DeviceStatusDto;
import com.cjkj.equipment.domain.vo.EquipmentVo;
import com.cjkj.equipment.mapper.EquipmentMapper;
import com.cjkj.equipment.service.IEquipmentService;
import com.cjkj.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 设备信息Service业务层处理
 * 
 * @author cjkj
 * @date 2024-08-15
 */
@Slf4j
@Service
public class EquipmentServiceImpl implements IEquipmentService
{
    @Resource
    private EquipmentMapper equipmentMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public boolean updateEquipmentStatus(DeviceStatusDto statusDto) {

        Equipment equipment = equipmentMapper.selectByEquipmentNo(statusDto.getDeviceName());
        if(equipment != null) {
            if("online".equals(statusDto.getStatus())) {
                equipment.setEquipmentStatus(0);
                equipment.setLastOnlineTime(statusDto.getTime());
            } else if("offline".equals(statusDto.getStatus())){
                equipment.setEquipmentStatus(1);
                equipment.setLastOfflineTime(statusDto.getTime());
            }
            int i = equipmentMapper.updateEquipment(equipment);
            return i > 0;
        }

        return false;
    }

    @Override
    public Equipment getEquipment(String equipmentNo, String equipmentType) {
        return equipmentMapper.selectEquipment(equipmentNo, equipmentType);
    }

    /**
     * 查询设备信息列表
     * 
     * @param equipment 设备信息
     * @return 设备信息
     */
    @Override
    public List<EquipmentVo> selectEquipmentList(Equipment equipment)
    {
        return equipmentMapper.selectEquipmentList(equipment);
    }

    @Override
    public List<EquipmentVo> selectExportEquipmentList(Equipment equipment) {
        return equipmentMapper.selectExportEquipmentList(equipment);
    }

    /**
     * 新增设备信息
     * 
     * @param equipment 设备信息
     * @return 结果
     */
    @Override
    public int insertEquipment(Equipment equipment)
    {
        equipment.setCreateTime(DateUtils.getNowDate());
        return equipmentMapper.insertEquipment(equipment);
    }

    /**
     * 修改设备信息
     * 
     * @param equipment 设备信息
     * @return 结果
     */
    @Override
    public int updateEquipment(Equipment equipment)
    {
        return equipmentMapper.updateEquipment(equipment);
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentByIds(String ids)
    {
        return equipmentMapper.deleteEquipmentByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除设备信息信息
     * 
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentById(Long id)
    {
        return equipmentMapper.deleteEquipmentById(id);
    }

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Equipment selectEquipmentById(Long id)
    {
        return equipmentMapper.selectEquipmentById(id);
    }

    @Override
    public boolean checkEquipmentNoUnique(Equipment equipment) {
        long id = StringUtils.isNull(equipment.getId()) ? -1L : equipment.getId();
        Equipment info = equipmentMapper.selectByEquipmentNo(equipment.getEquipmentNo());
        if (StringUtils.isNotNull(info) && info.getId() != id) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String importData(List<EquipmentVo> equipmentList) {
        if (StringUtils.isNull(equipmentList) || equipmentList.isEmpty()) {
            throw new ServiceException("导入设备数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipmentVo vo : equipmentList) {
            String equipmentNo = vo.getEquipmentNo();
            String equipmentType = vo.getEquipmentType();

            try {
                // 验证设备类型
                SysDictData dictData = sysDictDataMapper.selectDictDataByTypeAndLabel("equipment_type", equipmentType);
                if(StringUtils.isNull(dictData)) {
                    failureNum ++;
                    failureMsg.append("<br/>").append(failureNum).append("、设备号：").append(equipmentNo).append("导入失败！")
                            .append("（设备类型：").append(equipmentType).append(" 不存在）");
                    continue;
                }

                // 验证是否已存在这个设备
                Equipment info = equipmentMapper.selectByEquipmentNo(equipmentNo);
                if (StringUtils.isNull(info)) {

                    Equipment equipment = new Equipment();
                    BeanUtils.copyBeanProp(equipment, vo);
                    equipment.setEquipmentType(dictData.getDictValue());
                    equipment.setCreateTime(DateUtils.getNowDate());
                    equipmentMapper.insertEquipment(equipment);

                    successNum ++;
                    successMsg.append("<br/>").append(successNum).append("、设备号：").append(equipmentNo).append("导入成功！");
                } else {
                    failureNum ++;
                    failureMsg.append("<br/>").append(failureNum).append("、设备号：").append(equipmentNo).append(" 已存在！");
                }
            } catch (Exception e) {
                failureNum ++;
                String msg = "<br/>" + failureNum + "、设备号：" + equipmentNo + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
